//
//  Dress.m
//  WeddingStoreFinder
//
//  Created by Macdev on 11/19/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Dress.h"
#import "POI.h"
#import "AppDelegate.h"

@interface Dress()

+ (Dress*) getDressByCustomId:(int)_customDressId;
+ (NSArray*) getDressesByStatus:(int)_status;
+ (void) saveDress:(NSDictionary*)dressDict;
+ (void) updateDress:(Dress*)dress withPoiDict:(NSDictionary*)dressDict;

- (void) deleteDress;

@end


@implementation Dress

@dynamic customDressId;
@dynamic dressDesc;
@dynamic currency;
@dynamic price;
@dynamic imageName;
@dynamic poi;
@dynamic dressStatus;
@dynamic isAvailable;


+ (void) processDressList:(id)JSONResult {
	@synchronized ([UIApplication sharedApplication]) {
		if ([JSONResult isKindOfClass:[NSDictionary class]]) {
			AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
			NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
			NSArray *dressArray = [JSONResult valueForKey:kJSON_response];
			for (NSDictionary *dressDict in dressArray) {
				Dress *dressToUpdate = [Dress getDressByCustomId:[[dressDict valueForKey:kJSON_id] intValue]];
				if (dressToUpdate) {
					
					[Dress updateDress:dressToUpdate withPoiDict:dressDict];
					
					
				} else {
					if ([[dressDict valueForKey:kJSON_status] intValue] != kPOIStatus_toDelete) {
						[Dress saveDress:dressDict];
					}
				}
				
			}
			// Commit the change.
			NSError *error;
			if (![managedObjectContext save:&error]) {
				NSLog(@"Exception(Dress-processDressList): %@", [error description]);
			}
			
			//delete POIs with toDelete status:
			NSArray *dressesToDelete = [Dress getDressesByStatus:kPOIStatus_toDelete];
			for (Dress *dressToDelete in dressesToDelete) {
				[dressToDelete deleteDress];
			}
			
		} else {
			return;
		}
	}
}

+ (Dress*) getDressByCustomId:(int)_customDressId {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dress" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"customDressId == %d", _customDressId];
	[fetchRequest setPredicate:predicate];
	
	// Edit the section name key path and cache name if appropriate.
	// nil for section name key path means "no sections".
	NSError *error = nil;
	NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	[fetchRequest release];
	if (error) {
		NSLog(@"Dress - getDressByCustomId - %@", [error localizedDescription]);
	}
	if ([result count] > 0) {
		Dress *retValue = [result objectAtIndex:0];
		return retValue;
	} else {
		return nil;
	}
}

+ (NSArray*) getDressesByStatus:(int)_status {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dress" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dressStatus == %d", _status];
	[fetchRequest setPredicate:predicate];
	
	// Edit the section name key path and cache name if appropriate.
	// nil for section name key path means "no sections".
	NSError *error = nil;
	NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	[fetchRequest release];
	if (error) {
		NSLog(@"Dress - getDressByCustomId - %@", [error localizedDescription]);
	}
	if ([result count] > 0) {
		return result;
	} else {
		return nil;
	}
}

+ (void) saveDress:(NSDictionary*)dressDict {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	Dress *dress = (Dress *)[NSEntityDescription insertNewObjectForEntityForName:@"Dress" inManagedObjectContext:managedObjectContext];
	[Dress updateDress:dress withPoiDict:dressDict];
}

+ (void) updateDress:(Dress*)dress withPoiDict:(NSDictionary*)dressDict {
	
	dress.customDressId = (NSNumber*)[dressDict valueForKey:kJSON_id];
	dress.dressDesc = [dressDict valueForKey:kJSON_description];
	dress.dressStatus = (NSNumber*)[dressDict valueForKey:kJSON_status];
	dress.currency = [dressDict valueForKey:kJSON_currency];
	dress.price  = (NSNumber*)[dressDict valueForKey:kJSON_price];
	dress.isAvailable = (NSNumber*)[dressDict valueForKey:kJSON_available];
	dress.imageName = [dressDict valueForKey:kJSON_imagename];
	
	POI *poi = [POI getPOIByCustomId:[[dressDict valueForKey:kJSON_poiid] intValue]];
	NSMutableSet *dresSet = [[NSMutableSet alloc] initWithSet:poi.dresses];
	[dresSet addObject:dress];
	poi.dresses = dresSet;
	[dresSet release];
	
}

#pragma mark -
#pragma mark indstance methods

- (void) deleteDress {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	[managedObjectContext deleteObject:self];
	NSError *error;
	if (![managedObjectContext save:&error]) {
		NSLog(@"Exception(POI-delete): %@", [error description]);
	}
}


@end
